package com.cqie.rbac.filter;

import com.cqie.rbac.util.AuthToken;
import com.cqie.rbac.exception.BusinessException;
import com.cqie.rbac.util.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author 夏兵
 * @Date 2021/9/17
 */
@Component
public class Myfilter extends AuthenticatingFilter {
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return new AuthToken(JwtUtils.getTokenByRequest((HttpServletRequest) servletRequest));
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        UsernamePasswordToken token = (UsernamePasswordToken) createToken(servletRequest, servletResponse);
        try {
            if (token == null) {
                throw new BusinessException("5000", "令牌为空");
            }
            Subject subject = getSubject(servletRequest, servletResponse);
            subject.login(token);
            return onLoginSuccess(token, subject, servletRequest, servletResponse);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, servletRequest, servletResponse);
        }
    }
}
